package com.qinglei.recoup.third.event;

import com.qinglei.recoup.system.domain.BedRadarBO;
import com.qinglei.recoup.system.domain.Event;
import com.qinglei.recoup.system.service.BedService;
import com.qinglei.recoup.system.service.EventService;
import com.qinglei.recoup.third.properties.FuXingProperties;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.format.DateTimeFormatter;

/**
 * 复星事件服务
 *
 * @author yujunwei
 * @datetime 2022-05-05 15:24
 */
@Service
@Slf4j
public class FuXingEventService {

    private volatile String authorization;

    private volatile Long authorization_updateTime = 0L;

    @Resource
    private FuXingProperties fuXingProperties;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private EventService eventService;

    @Autowired
    private BedService bedService;

    public String getAuthorization() {
        if (authorization != null && (authorization_updateTime + 7200L * 1000) > System.currentTimeMillis()) {
            return authorization;
        }

        synchronized (this) {
            if (authorization != null && (authorization_updateTime + 7200L * 1000) > System.currentTimeMillis()) {
                return authorization;
            }
            // 设置入参
            JSONObject postData = new JSONObject();
            postData.put("app_id", fuXingProperties.getAppId());
            postData.put("app_secret", fuXingProperties.getAppSecret());
            // 自定义请求头
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(postData, httpHeaders);
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    String.format("%s/fosun/server_app/login/", fuXingProperties.getDomainUrl()), HttpMethod.POST, httpEntity, String.class);
            JSONObject responseJsonObject = JSONObject.fromObject(responseEntity.getBody());
            // log.info("getAuthorization responseJsonObject: {}", responseJsonObject);
            if (responseJsonObject != null) {
                int code = responseJsonObject.getInt("code");
                if (code == 200) {
                    JSONObject dataJsonObject = (JSONObject) responseJsonObject.get("data");
                    authorization_updateTime = System.currentTimeMillis();
                    authorization = dataJsonObject.getString("authorization");
                    // log.info("getAuthorization authorization: {}, expires_time: {}", authorization, dataJsonObject.getLong("expires_time"));
                }
            }
        }

        return authorization;
    }

    /**
     * 发送报警信息事件处理方法
     *
     * @param event
     */
    @EventListener
    @Async
    public void sendAlarmInfoEventHandler(AlarmInfoEvent event) {
        log.info("sendAlarmInfoEventHandler event: {}", event);
        Event bedEvent = eventService.getById(event.getEventId());
        if (null == bedEvent) {
            log.warn("sendAlarmInfoEventHandler bedEvent not exist, event: {}", event);
            return;
        }
        if (fuXingProperties.getTenantId() != bedEvent.getTenantId()) {
            log.warn("sendAlarmInfoEventHandler tenantId is invalid, tenantId: {}", bedEvent.getTenantId());
            return;
        }
        BedRadarBO bed = bedService.getBedWithSn(bedEvent.getBedId());
        if (null == bed) {
            log.warn("sendAlarmInfoEventHandler bed or radar not exist, event: {}", event);
            return;
        }

        // 设置入参
        JSONObject postData = new JSONObject();
        postData.put("project_code", fuXingProperties.getProjectCode());
        postData.put("device_sn", bed.getSnCode());
        postData.put("alarm_time", bedEvent.getHappenTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        postData.put("reason", bedEvent.getContent());
        postData.put("status", "waiting");
        postData.put("source", "QL");
        postData.put("outer_no", String.valueOf(event.getEventId()));
        log.info("sendAlarmInfoEventHandler postData: {}", postData);
        // 自定义请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        String authorization = getAuthorization();
        // log.info("sendAlarmInfoEventHandler authorization: {}", authorization);
        httpHeaders.add("Authorization", "Bearer " + authorization);
        HttpEntity<JSONObject> httpEntity = new HttpEntity<JSONObject>(postData, httpHeaders);
        ResponseEntity<String> responseEntity = restTemplate.exchange(
                String.format("%s/fosun/external/alarm_order/create/", fuXingProperties.getDomainUrl()), HttpMethod.POST, httpEntity, String.class);
        JSONObject responseJsonObject = JSONObject.fromObject(responseEntity.getBody());
        log.info("sendAlarmInfoEventHandler responseJsonObject: {}", responseJsonObject);
    }

}
